package com.lyb269.thread;

/**
 * Object wait(),notify()模拟生产者消费者模式,学习线程之间的协作
 */
public class ObjectWaitAndNotifyTest {

    public static void main(String[] args) {
        //定义锁
        Object obj = new Object();
        //此值通过 wait notify 模拟生产者消费者模式来等待赋值
        final String[] testVal = {"Init"};
        new Thread(() -> {
            Thread currentThread = Thread.currentThread();
            String threadName = currentThread.getName();
            System.out.println("执行线程:"+currentThread.getName()+";线程状态:"+currentThread.getState().name());
            synchronized (obj){
                System.out.println(threadName+" get lock!;线程状态:"+currentThread.getState().name());
                System.err.println(threadName+":testVal的值为:"+ testVal[0]+";线程状态:"+currentThread.getState().name());
                try {
                    Thread.sleep(1000);
                    System.out.println(threadName+" wait;线程状态:"+currentThread.getState().name());
                    // wait
                    obj.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.err.println(threadName+":wait后testVal的值为:"+ testVal[0]+";线程状态:"+currentThread.getState().name());
                System.out.println(threadName+" interrupt,结束挂起");
                currentThread.interrupt();
            }
        }).start();

        new Thread(() -> {
            Thread currentThread = Thread.currentThread();
            String threadName = currentThread.getName();
            System.out.println("执行线程:" + threadName+";线程状态:"+currentThread.getState().name());
            synchronized (obj) {
                System.out.println(threadName + " get lock!;线程状态:"+currentThread.getState().name());
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                testVal[0] = "Hello World!";
                System.err.println(threadName + ":为testVal赋值为:" + testVal[0]+";线程状态:"+currentThread.getState().name());
                System.out.println(threadName+" notify;线程状态:"+currentThread.getState().name());
                obj.notify();
                System.out.println(threadName+"执行结束;线程状态:"+currentThread.getState().name());
            }
        }).start();


        //执行线程:Thread-0;线程状态:RUNNABLE
        //Thread-0:testVal的值为:Init;线程状态:RUNNABLE                    &&&&
        //Thread-0 get lock!;线程状态:RUNNABLE
        //执行线程:Thread-1;线程状态:RUNNABLE
        //Thread-0 wait;线程状态:RUNNABLE
        //Thread-1 get lock!;线程状态:RUNNABLE
        //Thread-1:为testVal赋值为:Hello World!;线程状态:RUNNABLE           &&&&
        //Thread-0:wait后testVal的值为:Hello World!;线程状态:RUNNABLE       &&&&
        //Thread-1 notify;线程状态:RUNNABLE
        //Thread-1执行结束;线程状态:RUNNABLE
        //Thread-0 interrupt,结束挂起
    }
}
